package com.ruoyi.business.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DoneServiceImpl implements IDoneService {

    @Autowired
    private IProcessService processService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private IServiceItemService serviceItemService;


    @Override
    public List<CarPackageAudit> findDoneList(CarPackageAudit carPackageAudit) {
        long count = processService.selectDoneTaskCount(CarPackageAudit.DEFINITION_KEY,ShiroUtils.getUserId().toString());
        if(count>0){
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            List<HistoricTaskInstance> taskList = processService
                    .selectDoneTaskList(CarPackageAudit.DEFINITION_KEY,
                            ShiroUtils.getUserId().toString(),
                            (pageNum-1)*pageSize,
                            pageSize);
            //3.遍历待办任务,查询对应的CarPackAgeAudit
            List<CarPackageAudit> resultList = new ArrayList<>();
            CarPackageAudit audit;
            for (HistoricTaskInstance task : taskList) {
                HistoricProcessInstance historicProcessInstance = processService
                        .getHistoricProcessInstanceById(task.getProcessInstanceId());
                String businessKey = historicProcessInstance.getBusinessKey();
                audit = carPackageAuditService.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
                audit.setTaskName(task.getName());
                audit.setDoneTime(task.getEndTime());
                audit.setTaskId(task.getId());
                resultList.add(audit);
            }
            Page<CarPackageAudit> list = new Page<>();
            list.setTotal(count);
            list.setPageNum(pageNum);
            list.setPageSize(pageSize);
            list.addAll(resultList);
            return list;
        }else{
            return Collections.EMPTY_LIST;
        }
    }
}
